package com.qidian.permission.service.Impl;

import com.qidian.permission.entity.User;
import com.qidian.permission.mapper.UserMapper;
import com.qidian.permission.service.UserService;
import com.qidian.permission.util.entity.Pager;
import com.qidian.permission.util.entity.PerResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @Author 18林梦雅
 * @Company 起点编程
 * @Time 2023/10/18 17:58
 * @Description
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public PerResult queryById(Long userId) {
        /**
         *实现:是否根据id查询到数据
         */
        User user=null;
        if(Objects.nonNull(user=(userMapper.selectById(userId)))){
            return PerResult.ok(user);
        }
        return PerResult.empty();
    }

    /**
     * 添加用户,先判断用户名是否重复,再添加
     * @param user
     * @return
     */
    @Override
    public PerResult addUser(User user) {
        if(Objects.isNull(userMapper.selectByUsername(user.getUsername()))){
          return PerResult.updateIsOk(userMapper.addUser(user));
        }
        return PerResult.duplicate("用户名重复");
    }

    /**
     * 多条件分页查询
     * @param user
     * @param page
     * @param limit
     * @return
     */
    @Override
    public PerResult queryByPage(User user, int page, int limit) {
        Pager<User> pager=new Pager<>();
        pager.setCurr(page);
        pager.setLimit(limit);
        pager.setTotal( userMapper.selectCount(user));
        pager.setData(userMapper.selectByPage(user,(page-1)*limit,limit));
        pager.setMaxPageNum((int) Math.ceil(pager.getTotal()*1.0/limit));
        return PerResult.ok(pager);

    }

    /**
     * 根据用户id-->用户修改编辑
     * @param user
     * @return
     */
    @Override
    public PerResult update(User user) {
        //先判断用户输入的是否和本身相同,相同返回重复提示,不同则修改
//        user.getUsername().equals(userMapper.selectById(user.getUserId()))

//        先查询输入的名字是否存在,存在并且输入的id与查询到的存在的名字的id相同的话数据库自动更新修改时间
//        查询到名字存在,但不与本身相同则为名字重复了

        User userTemp=userMapper.selectByUsername(user.getUsername());
        if(userTemp!=null&&!userTemp.getUserId().equals(user.getUserId())){
            return PerResult.duplicate("用户名重复");
        }
        return PerResult.updateIsOk(userMapper.update(user));

    }

    @Override
    public PerResult deleteUpdateStatus(Long userId) {
        return PerResult.ok(userMapper.deleteUpdateStatus(userId));
    }

    @Override
    public PerResult deleteUpdateSelect(Long[] userIds) {
        int count=userMapper.deleteUpdateSelect(userIds);
        return PerResult.ok(count+" ");
    }


}
